<template>
  <el-dialog title="编辑"  :close-on-click-modal="false" 
  :visible.sync="show" class="dialog_index dialog_banner dialog_image"
   :before-close="cancle" v-loading="loading">
      <el-form ref="addForm"  class="article_manage_form" :rules="rules" :model="form">
       <p class="article_manage_form_title">基础资料</p>
       <div class="upload_module">
          <el-form-item prop="image" >
            <p  class="article_form_title">首图：</p>
            <el-upload  action="/api/api/general/upload"   class="upload-banner"
            :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, item)"
              :on-error="handleBannerError" :before-upload="beforeBannerUpload"
            :show-file-list="false" accept=".png,.jpg,.jpeg " :data="{type:'article', imageheight: imgH, imagewidth: imgW}" >
              <el-button size="small" type="primary" @click="isFirstDrawer">图库选择</el-button>
              <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              <div class="pop_container">
                <img v-if="form.image" :src="utils.setCdnUrl() + form.image" class="pop_image">
                <p class="tip" v-else>建议上传.png/.jpg/.jpeg格式，且尺寸比例为4:3，大小≤1M，每次只能上传一个</p>

              </div>

            </el-upload>
          </el-form-item>

          <div class="upload_info">
             <p class="article_form_title">基本信息：</p>
            <el-form-item class="multi_row" prop="title">
              <el-input type="textarea" resize="none"  @keydown.native="listen($event)"  placeholder="文章标题（必填项）" :rows="3" v-model="form.title"></el-input>
            </el-form-item>
            <el-form-item class=""  prop="first_type">
              <el-select   placeholder="一级类型（必填项）" v-model="form.first_type" @focus="getFirstTypeList"  >
                <el-option v-for="product in firstTypeList" :key="product.value" :value="product.value" :label="product.label"></el-option>
              </el-select>
            </el-form-item>
             
            <el-form-item prop="link">
              <el-input  placeholder="设置链接（必填项）" v-model="form.link"></el-input>
            </el-form-item>
          </div>

          <el-form-item prop="image_head" class="upload-image">
            <p  class="article_form_title">文章头图：</p>
            <el-upload  action="/api/api/general/upload"   class="upload-banner "
            :on-success="(response, file, fileList) => handleImageSuccess(response, file, fileList, item)"
              :on-error="handleImageError" :before-upload="beforeImageUpload"
            :show-file-list="false" accept=".png,.jpg,.jpeg " :data="{type:'article_image_head', imageheight: imgH, imagewidth: imgW}" >
              <el-button size="small" type="primary" @click="isOtherDrawer">图库选择</el-button>
              <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
              <div class="pop_container">
                <img v-if="form.image_head" :src="utils.setCdnUrl() + form.image_head" class="pop_image">
                <p class="tip" v-else>建议上传.png/.jpg/.jpeg格式，且尺寸比例为2:1，大小≤1M，每次只能上传一个</p>

              </div>

            </el-upload>
          </el-form-item>

       </div>
       <p class="article_manage_form_title">文章编辑</p>
        <el-form-item prop="article_editor" class="article_editor">
          <tinymce_editor v-model="form.article_editor"  :disabled="disabled"  @onClick="clickEditor" ref="editor"></tinymce_editor>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="search" :loading="isSubmit" @click="!isSubmit && submitForm()">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </span>
      <Drawer v-show="showDrawer" :type="type" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>
  </el-dialog>
  
</template>

<script>
import TinyMce from '@/components/Tinymce' 
import { firstTypeList } from '@/api/article/article_type.js'
import { articleManageEditGet, articleManageEditPost } from '@/api/article/article_manage.js'
import Drawer  from '@/components/Gallery/index.vue' 
export default {
  data () {
    return  {
      loading: false,
      imgH: '',
      imgW: '',
      form: {
        title: '',
        first_type: '',
        link: '',
        image: '',
        tag_type: '',
        image_head: ''
      },
      rules:{
        title:[
          { required: true, message: '字段文章标题为必填项', trigger: 'blur' },
          { min: 1, max: 100, message: '字段文章标题最多100字符', trigger: 'blur' }
        ],
        first_type:[
          { required: true, message: '字段一级类型为必填项', trigger: 'change' },
        ],
        link:[
          { required: true, message: '字段链接为必填项', trigger: 'blur' },
        ],
        image:[
          { required: true, message: '字段首图为必填项', trigger: 'change' },
        ],
        image_head:[
          { required: true, message: '文章头图为必填项', trigger: 'change' },
        ],
      },
      firstTypeList: [],
      disabled: false,
      showDrawer: false,
      isFirst: false,
      type: 'article', 
      isSubmit: false,
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number
  },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.isSubmit = false
        this.getArticleManage()
      }
    }
  },
  components:{tinymce_editor: TinyMce, Drawer},
  methods: {
    isFirstDrawer () {
      this.showDrawer = true
      this.isFirst = true
      this.type ='article'
    },
    isOtherDrawer () {
      this.isFirst = false
      this.type ='article_image_head'
      this.showDrawer = true

    },
        // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if(!this.isFirst) { // 头图
        this.form.image_head = data.filePathName
      } else { //首图
        this.form.image = data.filePathName
      }
      
    },
    handleImageSuccess (response) {
      this.form.image_head = response.data.filePathName
      this.$message.success('上传头图成功') 
    }, 
    handleImageError(){
      this.$message.error('上传头图失败')   
    },
    beforeImageUpload(file){
      let that = this
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg' &&  file.type !== 'image/png'){
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片")
        return false
      }
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传头图大小不超过1M")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          console.log(img.width,img.height)
          // let valid = img.width == '1920' &&   img.height == '937' ;
          let valid = true
          valid ? resolve() : reject();
          let imgW = img.width
          let imgH = img.height
          if (imgW > imgH && imgW >  imgH * 2 / 1) {
            that.imgW = imgH * 2 / 1
            that.imgH = imgH
          } else {
            that.imgH = imgW * 1 / 2
            that.imgW = imgW
          } 
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        // that.$message.error('上传图标尺寸为1920*937px')
        return Promise.reject()
      })
      return isSize
    },
    listen (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    },
    getArticleManage () {
      let params = {
        id: this.id
      } 
      articleManageEditGet(params).then(res=>{
        if (res.state == 1 ){
          this.form = res.data
        }
        this.loading = false
      })
    },
    handleBannerSuccess (response) {
      this.form.image = response.data.filePathName
      this.$message.success('上传图片成功')   
    },
    
    handleBannerError(){
      this.$message.error('上传图片失败')   
    },
    beforeBannerUpload(file){
      let that = this
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg' &&  file.type !== 'image/png'){
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片")
        return false
      }
      const isLt2M = file.size / 1024  <=  1024;
      if(!isLt2M){
        this.$message.error("上传图片大小不超过1M")
        return false
      }
      const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          console.log(img.width,img.height)
          // let valid = img.width == '1920' &&   img.height == '937' ;
          let valid = true
          valid ? resolve() : reject();
          let imgW = img.width
          let imgH = img.height
          if (imgW > imgH) {
            that.imgW = imgH * 4 / 3
            that.imgH = imgH
          } else if (imgW <=  imgH) {
            that.imgH = imgW * 3 / 4
            that.imgW = imgW
          } 
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        // that.$message.error('上传图标尺寸为1920*937px')
        return Promise.reject()
      })
      return isSize
    },
    clickEditor (event) {
      console.log(event)
    },

    getFirstTypeList(){
      firstTypeList().then(res=>{
        this.firstTypeList = res.data
      })
    },
    editArticleManage () {
      this.isSubmit = true
      let params = this.form
      articleManageEditPost(params).then(res=>{
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
        this.isSubmit = false
      })
    },
    submitForm () {
     this.$refs.addForm.validate((valid) => {
        if (valid ) {
          this.editArticleManage()
        } 
      })
    },
    cancle(){
      // this.$refs.addSiteFrom.clearValidate();
      this.$refs.addForm.resetFields(); // 清空原来的数据
      this.$emit('closeDialog')

    },
  }
}
</script>

<style>

</style>